import { defineStore } from "pinia";
import { postAction } from "src/utils/requestAction";
import { RouterParser } from "src/utils/routerParser";
import { RawUserMenuParser } from "src/utils/RawUserMenuParser";
import { HandleAsideMenu, TreeToArray } from "src/utils/arrayAndTree";

export const usePermissionStore = defineStore("permission", {
  state: () => ({
    userMenu: [],
    topMenu: [],
    userRouter: [],
  }),
  getters: {},
  actions: {
    async GetUserMenu() {
      const res = await postAction("user/get-user-menu");
      if (res.code === 1) {
        this.ClearMenu();
        const rawUserMenuData = res.data.records;
        console.log(rawUserMenuData);

        // 粗加工用户菜单数据
        const userMenuMiddle = RawUserMenuParser(rawUserMenuData);
        console.log("粗加工用户菜单数据：", userMenuMiddle);

        // 重组路由，针对component整理成路由（模板路由在routes.js已经预先定义了）
        const userRouter = RouterParser(userMenuMiddle);
        this.InitUserRouter(userRouter);
        console.log("userRouter: ");
        console.log(userRouter);

        // 重组分组菜单
        const topMenu = [];

        console.log("HandleAsideMenu: ");
        console.log(
          HandleAsideMenu(
            userMenuMiddle.filter((item) => item.need_by_topmenu === true),
            "menu_code",
            "parent_code"
          )
        );
        HandleAsideMenu(
          userMenuMiddle.filter((item) => item.need_by_topmenu === true),
          "menu_code",
          "parent_code"
        )
          .filter(
            (item) => item.parent_code === null || item.parent_code === ""
          )
          .forEach((item) => {
            if (item.children && item.children.length) {
              // console.log(item.children);
              topMenu.push({
                top: item,
                treeChildren: item.children.filter(
                  (item) => item.hidden !== "yes"
                ),
                arrayChildren: TreeToArray(item.children),
              });
            } else {
              topMenu.push({
                top: item,
              });
            }
          });
        console.log("topMenu: ");
        console.log(topMenu);
        // 设置顶部分组菜单详情
        this.InitTopMenu(topMenu);

        // 返回鉴权路由表
        return userRouter;
      } else {
        return;
      }
    },
    InitTopMenu(topMenu) {
      this.topMenu = topMenu;
    },
    InitUserRouter(userRouter) {
      this.userRouter = userRouter;
    },
    InitUserMenu(rawMenuData) {},
    ClearMenu() {
      this.userMenu = [];
      this.topMenu = [];
      this.userRouter = [];
    },
  },
});
